package appx.craft.droid.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import appx.craft.droid.R;
import appx.craft.droid.bean.FeedBean;
import appx.craft.droid.uc.ActivityBottomBar;
import appx.craft.droid.uc.ActivityTopMenu;
import appx.craft.droid.uc.FeedAdapter;
import appx.craft.droid.uc.FragmentSliderPager;
import appx.craft.droid.uc.ITapOnImageListener;
import appx.craft.droid.uc.OnActivityMenuListener;
import appx.craft.droid.utils.Constance;
import appx.craft.droid.utils.Log;
import appx.craft.droid.utils.UtilityHelper;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.download.ImageDownloader;
import com.nostra13.universalimageloader.utils.IoUtils;

/**
 * This class is used for sliding screen of feed download images and save in to local   
 *
 */
public class SlideShowActivity extends FragmentActivity implements
		OnActivityMenuListener,ITapOnImageListener {

	private final String TAG = SlideShowActivity.class.getCanonicalName();
	private SliderPagerAdapter mSliderAdapter;
	private ViewPager mPhotoViewPager;
	private int mCurrentPosition;

	private ActivityTopMenu mCustomTopMenu;

	private ActivityBottomBar mCustomBottomBar;

	public float currentXPosition;
	public float currentYPosition;
	
	public boolean isImageInLocal;
	
	public static ArrayList<FeedBean> mArrayListFeeds;
	
	int UploadCounter = 0;
	
	@Override
	protected void onCreate(Bundle saveInstance) {
		super.onCreate(saveInstance);
		setContentView(R.layout.activity_slidshow);
		Log.d(TAG, "[ onCreate ]");

		mArrayListFeeds = new ArrayList<FeedBean>();
		for (FeedBean mTemp : FeedAdapter.mFeedMessageList) {
			
			if(!mTemp.isFlagIsNew() && !mTemp.isFlagIsUpLoadedCancel()){
				
				mArrayListFeeds.add(mTemp);
				
			}else{
				UploadCounter++;
			}
			
		}

		mCurrentPosition = Integer.parseInt(getIntent().getStringExtra(
				Constance.INTENT_PHOTO_POSITION));
		
		if (mCurrentPosition > UploadCounter) {
			mCurrentPosition = ((mCurrentPosition-UploadCounter));	
		}else if(mCurrentPosition == UploadCounter){
			mCurrentPosition = 0;
		}
		
		
		mSliderAdapter = new SliderPagerAdapter(getSupportFragmentManager(),
				mArrayListFeeds.size());
		mPhotoViewPager = (ViewPager) findViewById(R.id.viewpager_photo_slider);
		mPhotoViewPager.setAdapter(mSliderAdapter);

		mPhotoViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int state) {
				mCurrentPosition = state;
				AppHandler.sendMessage(AppHandler.obtainMessage(0));
			}
			
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			}
			
			@Override
			public void onPageScrollStateChanged(int position) {
				
			}
		});
				
		// set current position
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				
				mPhotoViewPager.setCurrentItem(mCurrentPosition);
				
				
			}
		});

		mCustomTopMenu = new ActivityTopMenu(SlideShowActivity.this,
				getLayoutInflater());

		mCustomBottomBar = new ActivityBottomBar(SlideShowActivity.this,
				getLayoutInflater());

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.d(TAG, "[ onSaveInstanceState ] ");
		outState.putString(Constance.INTENT_PHOTO_POSITION,
				String.valueOf(mCurrentPosition));
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		Log.d(TAG, "[ onRestoreInstanceState ] ");
		mCurrentPosition = Integer.parseInt(savedInstanceState
				.getString(Constance.INTENT_PHOTO_POSITION));
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG, "[ onStart ]");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "[ onResume ]");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "[ onPause ]");
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.d(TAG, "[ onRestart ]");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "[ onStop ]");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		hidingMenu();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_MENU) {
			PerformMenu();
			return true; // always eat it!
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mCustomTopMenu.isShowing()) {
				mCustomTopMenu.hide();
				if (mCustomBottomBar.isShowing()) {
					mCustomBottomBar.hide();
				}
				return true;
			}

		}

		return super.onKeyDown(keyCode, event);
	}

	private class SliderPagerAdapter extends FragmentStatePagerAdapter {

		private final int mSize;

		public SliderPagerAdapter(FragmentManager fm, int size) {
			super(fm);
			mSize = size;
		}

		@Override
		public Fragment getItem(int position) {
			return FragmentSliderPager.newInstance(position);
		}

		@Override
		public int getCount() {
			return mSize;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			super.destroyItem(container, position, object);
		}
	}

	private void PerformMenu() {

		if (mCustomTopMenu.isShowing()) {
			mCustomTopMenu.hide();
		} else {

			findViewById(R.id.main_layout).post(new Runnable() {
				public void run() {
					mCustomTopMenu.show(findViewById(R.id.main_layout),
							mCurrentPosition, mArrayListFeeds);
				}
			});

		}

		if (mCustomBottomBar.isShowing()) {
			mCustomBottomBar.hide();
		} else {

			findViewById(R.id.main_layout).post(new Runnable() {
				public void run() {
					mCustomBottomBar.show(findViewById(R.id.main_layout),
							mCurrentPosition, mArrayListFeeds);

				}
			});

		}

	}

	private void hidingMenu() {

		if (mCustomTopMenu.isShowing()) {
			mCustomTopMenu.hide();
		}
		if (mCustomBottomBar.isShowing()) {
			mCustomBottomBar.hide();
		}
	}

	@Override
	public void onButtonSelected(int id) {
		if (id == R.id.btn_next) {

			if (mArrayListFeeds != null
					&& mCurrentPosition < mArrayListFeeds.size() - 1) {
				mCurrentPosition++;
//				Toast.makeText(getApplicationContext(), mCurrentPosition + "",
//						Toast.LENGTH_SHORT).show();
				// set current position
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						mPhotoViewPager.setCurrentItem(mCurrentPosition);
						AppHandler.sendMessage(AppHandler.obtainMessage(0));
					}
				});
			}

		} else if (id == R.id.btn_prv) {

			if (mArrayListFeeds != null && mCurrentPosition > 0) {
				mCurrentPosition--;
//				Toast.makeText(getApplicationContext(), mCurrentPosition + "",
//						Toast.LENGTH_SHORT).show();
				// set current position
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						mPhotoViewPager.setCurrentItem(mCurrentPosition);
						AppHandler.sendMessage(AppHandler.obtainMessage(0));
					}
				});

			}
		}else if(id == R.id.btn_save_local){
			
			
			AlertDialog.Builder builder = new AlertDialog.Builder(SlideShowActivity.this);
			builder.setMessage("Are you wise to save ? ");
			// Add the buttons
			builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
			           public void onClick(final DialogInterface dialog, int id) {
			               // User clicked OK button
			        	   FeedBean mTemmpBeen = mArrayListFeeds.get(mCurrentPosition);
			        	   
			        	   if(mTemmpBeen.getTypeID().equalsIgnoreCase(Constance.VIEW_UPLOAD)){
			        		   	isImageInLocal  = true;
			        	   }else if(mTemmpBeen.getTypeID().equalsIgnoreCase(Constance.VIEW_DOWNLOAD)){
			        		   	
			        			File cachedImage = ImageLoader.getInstance().getDiscCache().get(mArrayListFeeds.get(mCurrentPosition).getFilePath());
					   			if(cachedImage.exists()){
					   				isImageInLocal  = true;
					   				//Toast.makeText(getApplicationContext(),"File is exists",Toast.LENGTH_SHORT).show();
					   			}else{
					   				isImageInLocal  = false;
					   				//Toast.makeText(getApplicationContext(),"File Not exists",Toast.LENGTH_SHORT).show();
					   			}
					   			
			        	   }
			        	   
				   			AsyncTask<Void,Void, Integer> mSaveLocal = new AsyncTask<Void, Void, Integer>() {
				   				
								@Override
								protected void onPreExecute() {
									super.onPreExecute();
									if(mCustomBottomBar != null){
										mCustomBottomBar.startSave();
									}
								}
								
								@Override
								protected Integer doInBackground(Void... params) {
										int result = 0;
									try{
										
											FeedBean mTempBean = mArrayListFeeds.get(mCurrentPosition);
											if(mTempBean != null){
												
												File fileForSave = new File(Constance.IMAGE_DIR,UtilityHelper.extractFileName(mTempBean.getFilePath()));
												InputStream sourceStream = null;
											
											    if (isImageInLocal) { 
											    	
											    	if(mTempBean.getTypeID().equalsIgnoreCase(Constance.VIEW_DOWNLOAD)){
											    		sourceStream = new FileInputStream(ImageLoader.getInstance().getDiscCache().get(mTempBean.getFilePath()));	
											    	}else if(mTempBean.getTypeID().equalsIgnoreCase(Constance.VIEW_UPLOAD)){
											    		sourceStream = new FileInputStream(mTempBean.getFilePath());
											    	}
											        
											        
											    } else {
											    	// otherwise - download image
											        ImageDownloader downloader = new BaseImageDownloader(SlideShowActivity.this);
											        sourceStream = downloader.getStream(new URI(mArrayListFeeds.get(mCurrentPosition).getFilePath()),"file");
											    }
											    
											    if(!fileForSave.exists()){
												    OutputStream targetStream = new FileOutputStream(fileForSave);
												    IoUtils.copyStream(sourceStream, targetStream);
												    targetStream.close();
												    sourceStream.close();
											    }else{
											    	return result = 501;
											    }
												
											}
										
									}catch (Exception e) {
										e.printStackTrace();
										return result = 401;
									}
									    
									return result;
								}
								
								@Override
								protected void onPostExecute(Integer result) {
									super.onPostExecute(result);
									mCustomBottomBar.stopSave();
									if(result == 0){
										Toast.makeText(getApplicationContext(),"File Save",Toast.LENGTH_LONG).show();
									}else if(result == 501){
										Toast.makeText(getApplicationContext(),"File already exists",Toast.LENGTH_LONG).show();
									}
									dialog.dismiss();
									
								}
							};
							
							mSaveLocal.execute();
				   			 
			           }
			       });
			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   dialog.dismiss();
			           }
			       });
			// Create the AlertDialog
			AlertDialog mSaveDialog = builder.create();
			
			mSaveDialog.show();
			
			
			
		}
	}

	private Handler AppHandler = new Handler() {

		public void handleMessage(Message msg) {

			// UPDATE BOTTOM BAR
			mCustomBottomBar.setNavigationControl(mCurrentPosition, mArrayListFeeds);
			// UPDATE TOP MENU
			mCustomTopMenu.setPageSize(mCurrentPosition, mArrayListFeeds);
			
		}
	};

	@Override
	public void onTapImageView(int position) {
		PerformMenu();
	}

	@Override
	public void closeMenu() {
		hidingMenu();
		finish();
	}

}
